using System;
using System.Web;

namespace Jaws.Core.Web
{
    public class SecureCookies : IHttpModule
    {
        #region Implementation of IHttpModule

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication" /> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += SecureAllCookies;
            context.PreSendRequestContent += SecureAllCookies;
        }

        /// <summary>
        /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule" />.
        /// </summary>
        public void Dispose()
        {
            //Nothing to Dispose of at this point.
        }

        private static void SecureAllCookies(object sender, EventArgs e)
        {
            var context = (sender as HttpApplication);

            if (context != null)
            {
                foreach (string cookie in context.Request.Cookies)
                {
                    //We need to ignore the Session cookie because it will throw errors.  I would like to have a better explanation but I don't have one.
                    if (context.Request.Cookies[cookie].Name.Contains("Session")) continue;
                    context.Request.Cookies[cookie].Secure = true;
                    context.Request.Cookies[cookie].Expires = DateTime.Now.AddMinutes(10);
                    context.Request.Cookies[cookie].HttpOnly = true;
                }
            }
        }

        #endregion
    }
}